<template>
  <div>
    <div class="mask"></div>
    <div class="clerk">
      <div>
        <p>营业员</p>
        <i class="el-icon-close" @click="close"></i>
      </div>

      <div style="padding: 15px">
        <div class="search">
          <p>编号</p>
          <el-input v-model="numberInput"></el-input>
          <p>姓名</p>
          <el-input v-model="sexNameInput"></el-input>
          <el-button @click="search" type="primary">搜索</el-button>
        </div>
        <el-table
          :data="tableData"
          style="width: 100%; margin: 15px 0"
          height="300px"
          :header-cell-style="{
            background: '#f4f4f4',
            padding: 0,
            height: '40px'
          }"
          :cell-style="{ padding: 0, height: '36px' }"
          @selection-change="handleSelectionChange"
          @select="handleCurrentChange"
          ref="multipleTable"
          @select-all="topAllSelect"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="personnelNo" label="编号"></el-table-column>
          <el-table-column prop="personnelName" label="姓名"></el-table-column>
          <el-table-column prop="commissionRate" label="比例">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.commissionRate"
                type="number"
                @blur="proportionBlur(scope.row)"
                :disabled="!scope.row.select"
                @change="InputValueChange(scope.row)"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
        <div style="float: right; margin-bottom: 10px">
          <el-button @click="close">取消</el-button>
          <el-button @click="handleKeepBtnClick" type="primary">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 基本接口的引入
import { query_vip_personnel_data_api } from '../../../../request/page_base_api/page_base_api.js'
export default {
  data() {
    return {
      a: true,
      arr: [],
      phone: '',
      tableData: [],
      flag: true,
      // 复选框选中保存的数组
      multipleSelection: [],
      // 保存，拼接选中的营业员
      str_yinyueyuan: '',
      newStr: '',
      // 编号输入框的值
      numberInput: '',
      // 姓名输入框的值
      sexNameInput: '',
      idList: [],
      currentIdList: [],
      inputChangeRowList: [],
      currentInputChangeRowList: [],
      muIdlist: []
    }
  },
  created() {
    this.query_vip_personnel_data()
  },
  methods: {
    /* 
        表格中顶部的全选按钮被点击的时候
    */
    topAllSelect(selection) {
      //  this.$refs.multipleTable.clearSelection() //用于多选表格，清空用户的选择
    },
    // 查询营业员的api
    async query_vip_personnel_data() {
      const { data: res } = await query_vip_personnel_data_api({
        directSaleNo: this.$store.state.currentStoreData.no
      })
      console.log(res, 'query_vip_personnel_data_api')
      res.data.forEach((item) => {
        item.select = false
      })
      this.tableData = res.data
      console.log(this.tableData, 'this.tabledata')
    },
    // 搜索按钮被点击的时候，触发的函数
    search() {
      // 判断搜索的逻辑
      if (this.numberInput && this.sexNameInput) {
        console.log('diyige')
        this.tableData = this.tableData.filter((item) => {
          return (
            item.personnelNo === this.numberInput &&
            item.personnelName === this.sexNameInput
          )
        })
      } else if (this.numberInput) {
        console.log('dierge')
        this.tableData = this.tableData.filter((item) => {
          return item.personnelNo === this.numberInput
        })
      } else if (this.sexNameInput) {
        console.log('disange')
        this.tableData = this.tableData.filter((item) => {
          return item.personnelNo === this.personnelName
        })
      }
    },
    // input输入框输入的值，发生改变的时候，触发的函数
    InputValueChange(row) {
      // -----------------之前的-------------------
      // if (this.flag) {
      //   this.multipleSelection.forEach((item) => {
      //     if (item.select && item.id !== row.id) {
      //       // item.commissionRate = null
      //       item.commissionRate = 0
      //     }
      //   })
      //   this.flag = false
      // -------------------结束的（去重）------------------
      this.idList.push(row.id)
      this.inputChangeRowList.push(row)
      let s1 = new Set(this.idList)
      let s2 = new Set(this.inputChangeRowList)
      // console.log(s1, 's1')
      // console.log(s2, 's2')
      this.currentIdList = [...s1]
      this.currentInputChangeRowList = [...s2]
      // console.log(this.currentIdList, 'currentIdList')
      // console.log(this.currentInputChangeRowList, 'currentInputChangeRowList')
      // 全部先变成数字类型
      this.multipleSelection.forEach((item) => {
        item.commissionRate = Number(item.commissionRate)
      })
      // 逻辑就是：用户一旦自己修改过的，那么都不能动，都让用户自己修改
      // 定义一个新数组,用来存multipleSelection.id 和 currentIdList 比较，到时候比较取不同的id（就是用户没有修改的数据）
      this.muIdlist = []
      this.multipleSelection.forEach((item) => {
        this.muIdlist.push(item.id)
      })
      //
      // console.log(this.muIdlist, 'muIdlist')
      // 过滤出不同的id，保存起来
      const getArr = getArrDifference(this.muIdlist, this.currentIdList)
      console.log(getArr, 'getArr')
      // 过滤出不同的id方法
      function getArrDifference(arr1, arr2) {
        return arr1.concat(arr2).filter(function (v, i, arr) {
          return arr.indexOf(v) === arr.lastIndexOf(v)
        })
      }
      // 用户改变的总数和
      let total = 0
      // 这个是遍历是为了拿到: 没有修改的剩下总数 = 1 - 用户改变的总数和
      for (const i1 of this.multipleSelection) {
        for (const i2 of this.currentIdList) {
          if (i1.id === i2) {
            //  let total += i1.commissionRate
            total += i1.commissionRate
          }
        }
      }

      // total向下取两位(用户改变的总数和)
      total = Math.floor(total * 100) / 100
      // console.log(total, '用户改变的总数')
      //
      // 这个是没有改变的要平均的数
      let neverNum =
        Math.floor(
          ((1 - total) /
            (this.multipleSelection.length - this.currentIdList.length)) *
            100
        ) / 100

      // console.log(neverNum, '这个是没有改变的要平均的数')

      //遍历数组，修改数据（要平均的数）
      for (const item of this.multipleSelection) {
        for (const item1 of getArr) {
          if (item.id === item1) {
            // 用户没有修改的数据项
            // console.log(item.id, 'item')
            // 赋值平均数（上面已经算好平均数，上面已经取好2位）
            item.commissionRate = neverNum
          }
        }
      }
      // 如果改变数 + 没有改变的数 < 1（再遍历一遍选中的数组） ,那么证明有除不尽，并、并且下单已经取余数，那么剩下的数，就要加到第一项
      let secondTotal = 0
      this.multipleSelection.forEach((item) => {
        secondTotal += item.commissionRate
      })
      // 取两位
      secondTotal = Math.floor(secondTotal * 100) / 100
      // console.log(secondTotal, 'secondTotal再遍历一次的总数')
      // 如果小于1，总是给第一位数加就行
      if (secondTotal < 1) {
        // console.log('小于1')
        let sheng_xia_num = Math.floor((1 - secondTotal) * 100) / 100
        this.multipleSelection[0].commissionRate =
          this.multipleSelection[0].commissionRate + sheng_xia_num
      }
    },
    // 当选择项发生变化时会触发该事件
    handleCurrentChange(selection, row) {
      // selection.length    0 开始 (第六个item删掉，否则计算出错)
      if (selection.length === 6) {
        selection.splice(5, 1)
      }
      // row是拿到状态被改变之前的状态值，第一次点击，拿到的都是select都是false
      console.log(selection, row.select, selection.length, 'CurrentChange')
      if (row.select) {
        console.log('进来了')
        row.commissionRate = null
        row.select = false
        if (selection.length === 1) {
          console.log('11111')
          row.select = true
          selection.forEach((item) => {
            item.commissionRate = 1
          })
          row.select = false
        } //

        if (selection.length === 2) {
          console.log('2222222')
          row.select = true
          selection.forEach((item) => {
            item.commissionRate = 0.5
          })
          row.select = false
        } //
        if (selection.length === 3) {
          console.log('33333')
          row.select = true
          // 后端要求的
          // selection.forEach((item) => {
          //   // item.commissionRate = 0.33
          // })
          selection[0].commissionRate = 0.4
          selection[1].commissionRate = 0.3
          selection[2].commissionRate = 0.3
          row.select = false
        }
        if (selection.length === 4) {
          console.log('4444')
          row.select = true
          selection.forEach((item) => {
            item.commissionRate = 0.25
          })
          row.select = false
        }
        if (selection.length === 5) {
          console.log('55555')
          row.select = true
          selection.forEach((item) => {
            item.commissionRate = 0.2
          })
          row.select = false
        }
        return
      } //   row.select = true //   如果没有选中了，那么第一个input也禁用，并且数据为空 // 如果》=5 就
      if (this.multipleSelection.length > 4) {
        //   一开始就是true，这里就应该变成false
        row.select = false
        return this.$refs.multipleTable.toggleRowSelection(row, false)
      }
      if (selection.length === 0) {
        console.log('changdu0') // row.select = false
        row.commissionRate = null
      } //
      if (selection.length === 1) {
        console.log('111111111')

        row.select = true
        selection.forEach((item) => {
          item.commissionRate = 1
        })
      }
      if (selection.length === 2) {
        console.log('2222222')
        row.select = true
        selection.forEach((item) => {
          item.commissionRate = 0.5
        }) //
      }
      if (selection.length === 3) {
        console.log('333333')

        row.select = true
        // 后端要求的
        // selection.forEach((item) => {
        //   // item.commissionRate = 0.33
        // }) //
        selection[0].commissionRate = 0.4
        selection[1].commissionRate = 0.3
        selection[2].commissionRate = 0.3
      }
      if (selection.length === 4) {
        console.log('444444')
        row.select = true
        selection.forEach((item) => {
          item.commissionRate = 0.25
        })
      }
      if (selection.length === 5) {
        console.log('5555')
        row.select = true
        selection.forEach((item) => {
          item.commissionRate = 0.2
        })
      }
      //   if (selection.length === 5) { //     row.select = true //     selection.forEach((item) => { //       item.commissionRate = 0.2 //     }) //   }
    },
    // 当用户手动勾选数据行的 Checkbox 时触发的事件
    handleSelectionChange(arr) {
      // 每次当用户自己再次勾选的时候，输入计算的所有方式都要清空
      this.muIdlist = []
      this.currentIdList = []
      this.currentInputChangeRowList = []
      this.idList = []
      this.inputChangeRowList = []
      //-------------------------------
      this.multipleSelection = arr
      if (this.multipleSelection.length <= 5) {
        arr.forEach((item1) => {
          const index = this.tableData.findIndex((item2) => {
            return item1.id === item2.id
          })
          if (index !== -1) {
            this.tableData.splice(index, 1)
          }
        })
        this.tableData.unshift(...arr)
      } //
    },

    // 关闭icon被点击的时候，触发函数
    close() {
      this.$emit('close_yingyueyuan_dialog')
    },

    // 点击保存按钮的时候，触发的函数
    handleKeepBtnClick() {
      // 计算一下，比例，比例不能超过1，超过的话，直接提示用户，不能关闭dialog
      const commissionRateSum = this.multipleSelection.reduce((pre, item) => {
        return pre + Number(item.commissionRate)
      }, 0)
      // console.log(commissionRateSum, 'commissionRateSum')
      if (commissionRateSum > 1) {
        return this.$message.warning('比例设置和不能超过1')
      }
      // console.log(this.multipleSelection, 'handleKeepBtnClick')
      // 拼接营业员添加并且用逗号“,”分割
      this.multipleSelection.forEach((item) => {
        this.str_yinyueyuan += item.personnelName + ','
      })
      // 去掉最后的','
      this.newStr = this.str_yinyueyuan.substr(
        0,
        this.str_yinyueyuan.length - 1
      )
      // console.log(this.newStr, 'personnelName')

      // console.log('okokok')
      // 点击保存的时候，拼接营业员的名字和拿到营业员的数组给父组件
      this.$emit('keepNewStr', this.newStr, this.multipleSelection)
      // 关闭弹出层
      this.close()
    },
    proportionBlur(row) {
      // console.log(row, 'proportionBlur')
    }
  }
}
</script>

<style lang="less" scoped>
// 隐藏表头全选按钮
/deep/.el-table__header-wrapper .el-checkbox {
  display: none;
}

.mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.3;
  z-index: 99;
}
.clerk {
  position: fixed;
  top: 20%;
  left: 50%;
  transform: translateX(-50%);
  width: 600px;
  z-index: 99;
  background-color: white;
  overflow: auto;
}
.clerk > div:first-child {
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  background: #f4f4f4;
  font-weight: 700;
}

.search {
  display: flex;
}
p {
  margin: 0;
}
</style>

<style>
.clerk .el-input,
.clerk .el-input__inner {
  width: 140px;
  height: 30px;
}
.clerk .el-input {
  margin: 0 10px;
}
</style>
